#!/bin/sh

if [ $# -ne 2 ]
then
    echo "usage: $0 <start|stop> <config>" >&2
    exit 1
fi

action=$1
config=$2

gadget_name=mass-storage
gadget_dir=/sys/kernel/config/usb_gadget/$gadget_name


set_usb_switch()
{
    gpio_chip=7
    gpio_num=24

    if [[ $1 == "OPEN" ]]
    then
        value=0
    elif [[ $1 == "DISCONNECT" ]]
    then
        value=1
    else
        return 0
    fi

    GPIO_BASE=(`ls /sys/class/gpio`)
    i=0
    while [ ${GPIO_BASE[${i}]} ]
    do
        GPIO_CHIP=${GPIO_BASE[${i}]#*gpiochip}

        GPIO_PATH="/sys/class/gpio/${GPIO_BASE[$i]}/device/gpiochip${gpio_chip}"
        if [ ! -e $GPIO_PATH ]
        then
            i=$((i+1))
            continue
        fi

        BASE=$(cat /sys/class/gpio/gpiochip${GPIO_CHIP}/base)
        CONTROL_GPIO=$((${BASE}+${gpio_num}))

        [ ! -d /sys/class/gpio/gpio${CONTROL_GPIO} ] && {
            echo $CONTROL_GPIO > /sys/class/gpio/export
        }

        echo "out" > /sys/class/gpio/gpio${CONTROL_GPIO}/direction
        echo ${value} > /sys/class/gpio/gpio${CONTROL_GPIO}/value

        echo $CONTROL_GPIO > /sys/class/gpio/unexport

        return 0;
    done
}



case "$config" in
0)
    nbd_device=/dev/nbd0
    ;;
1)
    nbd_device=/dev/nbd1
    ;;
*)
    echo "invalid config $config" >&2
    exit 1
    ;;
esac

set -ex

case "$action" in
start)
    if [ -e "${gadget_dir}" ]; then
        cd $gadget_dir
        echo $nbd_device > functions/mass_storage.usb0/lun.0/file
        exit 0
    fi
    mkdir -p $gadget_dir
    (
    cd $gadget_dir
    # http://www.linux-usb.org/usb.ids
    #    |-> 1d6b  Linux Foundation
    #          |-> 0104  Multifunction Composite Gadget
    echo "0x1d6b" > idVendor
    echo "0x0104" > idProduct
    mkdir -p strings/0x409
    echo "OpenBMC" > strings/0x409/manufacturer
    echo "Virtual Media Device" > strings/0x409/product
    mkdir -p configs/c.1/strings/0x409
    echo "config 1" > configs/c.1/strings/0x409/configuration
    mkdir -p functions/mass_storage.usb0
    ln -s functions/mass_storage.usb0 configs/c.1
    echo 1 > functions/mass_storage.usb0/lun.0/removable
    echo 1 > functions/mass_storage.usb0/lun.0/ro
    echo 0 > functions/mass_storage.usb0/lun.0/cdrom
    echo $nbd_device > functions/mass_storage.usb0/lun.0/file
    echo "31900000.usb2" > UDC
    set_usb_switch "OPEN"
    )
    ;;
stop)
    (
    set_usb_switch "DISCONNECT"
    cd $gadget_dir
    echo "" > UDC
    echo "" > functions/mass_storage.usb0/lun.0/file
    echo "31900000.usb2" > UDC
    set_usb_switch "OPEN"
    )
    ;;
*)
    echo "invalid action $action" >&2
    exit 1
esac

exit 0

